package org.osomit.sacct.server.wiring;

import com.google.inject.AbstractModule;
import com.google.inject.name.Names;

import java.util.Properties;
import java.net.URL;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.osomit.sacct.server.config.iface.ServerConfig;
import org.osomit.sacct.server.config.impl.ServerConfigImpl;

/**
 * @author Jian Fang (John.Jian.Fang@gmail.com)
 *
 * Date: Jul 4, 2009
 * 
 */
public class ServerConfigModule extends AbstractModule {
    public static final String SERVER_BASE = "server.base";

    @Override
    protected void configure() {
        // bind the properties
        try {
            Properties properties = loadProperties();
            java.util.Properties p = System.getProperties();
            String serverBase = p.getProperty(SERVER_BASE);
            //set the account File to the data directory
            if (serverBase != null && serverBase.trim().length() > 0) {
                String accountName = properties.getProperty("accountFileName");
                properties.setProperty("accountFileName", serverBase + "/data/" + accountName);
            }
            Names.bindProperties(binder(), properties);
            System.out.println("Loaded SAcct Server Configuration successfully");
        } catch (Exception e) {
            // handle the exception
            System.out.println("Error loading Server Configuration " + e.getMessage());
            System.out.println("Use Server Default Configuration.");
        }
    }

    private static Properties loadProperties() throws Exception {
        Properties properties = new Properties();
        String name = "sacct.properties";
        java.util.Properties p = System.getProperties();
        String serverBase = p.getProperty(SERVER_BASE);
        //set the sacct.properties to the conf directory
        if(serverBase != null && serverBase.trim().length() > 0){
            name = serverBase + "/conf/sacct.properties";
        }
        FileInputStream fin = new FileInputStream(name);
        BufferedReader br = new BufferedReader(new InputStreamReader(fin));
        properties.load(br);
        
        br.close();
        fin.close();
        
        System.out.println("Loading SAcct Server configuration from file " + name);

        return properties;
    }
}
